# encoding=utf8

import json
import pymysql,requests,urllib3,datetime,re
from lxml import etree
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

#目标：url=https://c.mi.com/global/miuidownload/index下的手机名称与Rom包下载地址

'''''MySQL配置'''
host = '127.0.0.1'
users = 'root'
pwd = '123123'
port = 3306
dbs = 'ans'

def mysql(phone_id, phone_name, version ,author, rom_url, size):
    value = ((phone_id, phone_name, version ,author, rom_url, size))
    db = pymysql.connect(host=host, user=users,passwd=pwd,port=port, db=dbs)
    cursor = db.cursor()
    sql = "INSERT INTO miui(phone_id, phone_name, version ,author, rom_url, size) values(%s,%s,%s,%s,%s,%s)"
    try:
        cursor.execute(sql, value)
        db.commit()
        print('success!')
    except Exception as e:
        db.rollback()
        print("error.", e)
    db.close()

def downtext(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.62',
        'Cookie':'APP_LOCAL=oc; MS2Y_409f_saltkey=WmxJ6Bx0; xm_bbs_oc_sid=7rlci7lmsdf73luefgkd8jd7j7; MS2Y_409f_sid=cOyP7F',
    }
    res = requests.get(url=url,headers=headers).text

    return res


def downjson(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.62',
        'Cookie':'APP_LOCAL=oc; MS2Y_409f_saltkey=WmxJ6Bx0; xm_bbs_oc_sid=7rlci7lmsdf73luefgkd8jd7j7; MS2Y_409f_sid=cOyP7F',
    }
    res = requests.post(url=url,headers=headers).json()


    return res

def func(res):
    for phone in res['data']['phone_data']['phone_list']:
        phone_id = phone['id']
        phone_name = phone['name']
        # print(phone_id,phone_name)
        phone_url = 'https://c.mi.com/oc/rom/getdevicelist?phone_id=' + phone_id
        res = downjson(phone_url)
        for version in res['data']['device_data']['device_list']:
            version = version
            resp = res['data']['device_data']['device_list'][version]['stable_rom']
            author = resp['author']
            rom_url = resp['rom_url']
            size = resp['size']
            print(phone_id, phone_name, version ,author, rom_url, size)
            mysql(phone_id, phone_name, version ,author, rom_url, size)

    return 0

if __name__ == "__main__":
        url = 'https://c.mi.com/oc/rom/getphonelist'
        res = downjson(url)
        #https://c.mi.com/oc/miuidownload/detail?device=1900386
        #https://c.mi.com/oc/miuidownload/detail?device=1900385
        func(res)
